package com.xzq.bugstack.client;

import com.googlecode.protobuf.format.JsonFormat;
import com.xzq.bugstack.domain.MsgBody;
import com.xzq.bugstack.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 12:49
 * @Version 1.0.0
 **/
public class MyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("连接建立...");
        System.out.println("服务端IP：" + sc.localAddress().getHostString());
        System.out.println("服务端端口：" + sc.localAddress().getPort());
        //通知客户端连接成功
        String str = "我连接上你了 服务端..... very ok";
        ctx.writeAndFlush(MsgUtil.buildMsg(sc.id().toString(), str));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开连接：" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("消息类型：" + msg.getClass());
        System.out.println("消息内容：" + JsonFormat.printToString((MsgBody)msg));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息： \r\n" + cause.getMessage());
    }
}
